<script setup lang="ts">
  import { useForm } from 'vee-validate';
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import * as yup from 'yup';
import securityIcon from '/images/webp/setting/verification_icon.webp';
import {  useField, Form } from 'vee-validate'
const { t } = useI18n()
const { isSetAuth, loadingAuthConfig, runMemberAuthConfig, singlePromiseArray } = useAuthConfig()
  definePageMeta({
    layout: 'header-back',
    title: 'double_verification'
})

const router = useRouter()

// 验证码相关
const verificationCode = ref('RER332FF3EFVDFBVDGREVDF434')
const loginPwd= ref('')
const tfaCode = ref('')

const schema = yup.object().shape({
  auth_code: yup.string().required(t('two_factor_enter_code')),
  password: yup.string().required(t('password_required')).matches(twoFactorReg, t('two_factor_password_verify')),
});

const { resetForm, setFieldValue, values } = useForm({
  validationSchema: schema,
  initialValues: {
    password: '',
    auth_code: ""
  }
})
/** 双重验证 */
const {
  value: loginPassword,
  errorMessage: loginPwdErrorMsg,
  validate: validateLoginPwd,
  resetField: resetLoginPassword,
} = useField<string>('loginPassword', fieldVerifyLoginPwd)
function fieldVerifyLoginPwd(value: string) {
  if (!value)
    return t('pls_enter_password')
  else if (value.length < 8)
    return t('password_least_8_characters')
  else if (!upperLowerReg.test(value))
    return t('password_uppercase_lowercase_letter')
  else if (!lastOneNumberReg.test(value))
    return t('password_least_1_number')
  return ''
}
const {
  value: doublePassword,
  errorMessage: doublePwdErrorMsg,
  validate: validateDoublePwd,
  resetField: resetDoublePassword,
} = useField<string>('doublePassword', (value) => {
  if (!value)
    return t('pls_input_double_check_pwd')
  return ''
})
  // 获取二阶段验证密钥
const {
  data: authQrcode,
  run: runMemberAuthQrcode,
} = useRequest(ApiMemberAuthQrcode, {
  onSuccess() {
  },
})
// 设定二阶段验证
const {
  run: runMemberAuthSet,
  loading: loadMemberAuthSet,
} = useRequest(ApiMemberAuthSet, {
  onSuccess() {
    runMemberAuthConfig()
    message.success('success_set_double_check')
    resetForm()
    resetLoginPassword()
    resetDoublePassword()
  },
})

// 关闭二阶段验证
const {
  run: runMemberAuthClose,
  loading: loadMemberAuthClose,
} = useRequest(ApiMemberAuthClose, {
  onSuccess() {
    runMemberAuthConfig()
    message.success(t('success_close_double_check'))
    resetForm()
    resetLoginPassword()
    resetDoublePassword()
  },
})

  // 复制验证码
  const copyCode = () => {
    application.copy(authQrcode.value?.secret ?? '', t)
    message.success(t('two_factor_code_copied'))
  }

async function submitDoublePassword() {
  await validateLoginPwd()
  await validateDoublePwd()
  const data = { password: values.password, auth_code: values.auth_code }
  isSetAuth.value ? runMemberAuthClose(data) : runMemberAuthSet(data)
}

watch(() => isSetAuth.value, (val) => {
  if (!val)
    runMemberAuthQrcode()
}, { immediate: true })

await application.allSettled(singlePromiseArray)
</script>

<template>
  <div class="tfa-page">
    <div class="tfa-content">
      <!-- 页面标题 -->
      <div class="page-title">{{ t('double_verification') }}</div>

      <!-- 双重验证部分 -->
      <div class="section tfa-section">
        <div class="section-item">
          <div class="content">
            <BaseImage width="28px" style="height: 28px;margin-bottom: 10px;" :url="securityIcon" />
            <div class="title">{{ t('double_verification') }}</div>

            <!-- 验证器应用提示 -->
            <div class="tip-text">
              {{ t('two_factor_copy_to_app') }}
            </div>

            <!-- 验证码显示区域 -->
            <div class="verification-code">
              <div class="code">{{ authQrcode?.secret ?? '' }}</div>
              <button class="copy-btn" @click="copyCode">{{ t('affiliate_program_copy') }}</button>
            </div>

            <!-- 提示文本 -->
            <div class="warning-text">{{ t('two_factor_warning') }}</div>

            <!-- QR码 -->
            <div class="qr-container">
              <div class="qr-code">
                <BaseQrcode :url="authQrcode?.qrcode || ''" :size="164"/>
              </div>
            </div>
            <Form :validation-schema="schema" @submit="submitDoublePassword">
              <BaseInput required class="mt-[1rem]" :label="t('two_factor_login_password')" name="password" type="password" :placeholder="t('password_required')">
              </BaseInput>
              <BaseInput required class="mt-[1rem]" :label="t('two_factor_enter_code')" name="auth_code" type="password" :placeholder="t('two_factor_enter_code')">
              </BaseInput>
              <BaseButton :loading="loadMemberAuthClose || loadMemberAuthSet" class="w-full h-[2.5rem] mt-[1rem] text-text-black-10 text-[.75rem]" html-type="submit">
                {{t('save')}}
              </BaseButton>
            </Form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .tfa-page {
    height: 94vh;
    background-color: #232626;
    color: #FFF;
    overflow-y: auto;
    padding: 16px;

    .page-title {
      font-size: 14px;
      font-weight: 500;
      padding: 10px 10px 15px 0;
      color: #fff;
      border-bottom: 1px solid var(--white-10010, #FFFFFF1A);
      margin-left: 10px;
    }

    .tfa-content {
      background-color: #323738;
      border-radius: 8px;
    }

    .section {
      padding: 16px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      padding-left: 20px;
      padding-bottom: 45px;

      &:last-child {
        border-bottom: none;
      }
    }

    .section-item {
      display: flex;
      align-items: flex-start;
      gap: 16px;

      .content {
        flex: 1;

        .title {
          font-size: 16px;
          font-weight: 500;
          margin-bottom: 16px;
          border-bottom: 1px solid var(--white-10010, #FFFFFF1A);
          padding-bottom: 14px;
        }

        .tip-text {
          font-size: 12px;
          color: #B3BEC1;
          margin-bottom: 12px;
        }

        .verification-code {
          display: flex;
          align-items: center;
          justify-content: space-between;
          background-color: #292D2E;
          border-radius: 6px;
          border: 1px solid var(---bg-black-53A4142, #3A4142);
          padding: 4px 6px 4px 12px;
          margin-bottom: 12px;

          .code {
            font-size: 14px;
            color: #fff;
            word-break: break-all;
            flex: 1;
            margin-right: 8px;
          }

          .copy-btn {
            min-width: 60px;
            height: 30px;
            background: linear-gradient(90deg, #24EE89 0%, #9FE871 100%);
            border: none;
            border-radius: 4px;
            color: #000;
            font-weight: 500;
            font-size: 12px;
            cursor: pointer;
          }
        }

        .warning-text {
          font-size: 12px;
          color: #B3BEC1;
          margin-bottom: 16px;
          text-align: left;
        }

        .qr-container {
          display: flex;
          justify-content: center;
          margin-bottom: 24px;

          .qr-code {
            width: 180px;
            height: 180px;
            background-color: #fff;
            border-radius: 8px;
            overflow: hidden;
            padding: 8px;
          }
        }

        .label {
          font-size: 12px;
          color: #B3BEC1;
          margin-bottom: 8px;
        }

        .input-row {
          margin-bottom: 16px;

          .password-input-container {
            position: relative;

            .eye-icon {
              position: absolute;
              right: 10px;
              top: 50%;
              transform: translateY(-50%);
              cursor: pointer;
              z-index: 10;
            }
          }

          .error-message {
            margin-top: 4px;
            font-size: 10px;
            color: #F56565;
          }
        }

        .button-row {
          margin-top: 24px;

          .save-btn {
            width: 100%;
            height: 40px;
            background: linear-gradient(90deg, #24EE89 0%, #9FE871 100%);
            border: none;
            border-radius: 6px;
            color: #000;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;

            &.disabled {
              opacity: 0.5;
              cursor: not-allowed;
            }
          }
        }
      }
    }
  }
</style>
